<template>
  <div class="condition-node-config">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="节点名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入节点名称" />
      </el-form-item>
      
      <el-form-item label="条件类型" prop="conditionType">
        <el-select v-model="form.conditionType" style="width: 100%" @change="onConditionTypeChange">
          <el-option label="响应状态码" value="status_code" />
          <el-option label="响应时间" value="response_time" />
          <el-option label="JSONPath" value="jsonpath" />
          <el-option label="响应头" value="header" />
          <el-option label="响应体包含" value="body_contains" />
          <el-option label="变量值" value="variable" />
          <el-option label="自定义表达式" value="custom" />
        </el-select>
      </el-form-item>

      <!-- 基于条件类型的配置 -->
      <div v-if="form.conditionType === 'status_code'">
        <el-form-item label="操作符" prop="operator">
          <el-select v-model="form.operator" style="width: 100%">
            <el-option label="等于" value="equals" />
            <el-option label="不等于" value="not_equals" />
            <el-option label="大于" value="greater_than" />
            <el-option label="小于" value="less_than" />
            <el-option label="大于等于" value="greater_equal" />
            <el-option label="小于等于" value="less_equal" />
          </el-select>
        </el-form-item>
        <el-form-item label="期望值" prop="expectedValue">
          <el-input-number v-model="form.expectedValue" :min="100" :max="599" style="width: 100%" />
        </el-form-item>
      </div>

      <div v-else-if="form.conditionType === 'response_time'">
        <el-form-item label="操作符" prop="operator">
          <el-select v-model="form.operator" style="width: 100%">
            <el-option label="小于" value="less_than" />
            <el-option label="大于" value="greater_than" />
            <el-option label="小于等于" value="less_equal" />
            <el-option label="大于等于" value="greater_equal" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间(毫秒)" prop="expectedValue">
          <el-input-number v-model="form.expectedValue" :min="0" style="width: 100%" />
        </el-form-item>
      </div>

      <div v-else-if="form.conditionType === 'jsonpath'">
        <el-form-item label="JSONPath" prop="targetPath">
          <el-input 
            v-model="form.targetPath" 
            placeholder="例如: $.data.status, $.user.id"
          >
            <template #suffix>
              <el-tooltip content="JSONPath表达式&#10;例如: $.data.status, $.user.id" placement="top">
                <el-icon style="cursor: help"><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="操作符" prop="operator">
          <el-select v-model="form.operator" style="width: 100%">
            <el-option label="等于" value="equals" />
            <el-option label="不等于" value="not_equals" />
            <el-option label="包含" value="contains" />
            <el-option label="不包含" value="not_contains" />
            <el-option label="大于" value="greater_than" />
            <el-option label="小于" value="less_than" />
            <el-option label="存在" value="exists" />
            <el-option label="不存在" value="not_exists" />
          </el-select>
        </el-form-item>
        <el-form-item label="期望值" prop="expectedValue" v-if="!['exists', 'not_exists'].includes(form.operator)">
          <el-input v-model="form.expectedValue" placeholder="期望的值 (支持变量: {variableName})" />
        </el-form-item>
      </div>

      <div v-else-if="form.conditionType === 'header'">
        <el-form-item label="响应头名称" prop="targetPath">
          <el-input v-model="form.targetPath" placeholder="例如: Content-Type, Authorization" />
        </el-form-item>
        <el-form-item label="操作符" prop="operator">
          <el-select v-model="form.operator" style="width: 100%">
            <el-option label="等于" value="equals" />
            <el-option label="包含" value="contains" />
            <el-option label="存在" value="exists" />
          </el-select>
        </el-form-item>
        <el-form-item label="期望值" prop="expectedValue" v-if="form.operator !== 'exists'">
          <el-input v-model="form.expectedValue" placeholder="期望的值" />
        </el-form-item>
      </div>

      <div v-else-if="form.conditionType === 'body_contains'">
        <el-form-item label="包含文本" prop="expectedValue">
          <el-input 
            v-model="form.expectedValue" 
            type="textarea" 
            :rows="3"
            placeholder="响应体中应包含的文本"
          />
        </el-form-item>
      </div>

      <div v-else-if="form.conditionType === 'variable'">
        <el-form-item label="变量名" prop="targetPath">
          <el-input v-model="form.targetPath" placeholder="例如: userId, token" />
        </el-form-item>
        <el-form-item label="操作符" prop="operator">
          <el-select v-model="form.operator" style="width: 100%">
            <el-option label="等于" value="equals" />
            <el-option label="不等于" value="not_equals" />
            <el-option label="包含" value="contains" />
            <el-option label="大于" value="greater_than" />
            <el-option label="小于" value="less_than" />
            <el-option label="存在" value="exists" />
            <el-option label="不为空" value="not_empty" />
          </el-select>
        </el-form-item>
        <el-form-item label="期望值" prop="expectedValue" v-if="!['exists', 'not_empty'].includes(form.operator)">
          <el-input v-model="form.expectedValue" placeholder="期望的值" />
        </el-form-item>
      </div>

      <div v-else-if="form.conditionType === 'custom'">
        <el-form-item label="自定义表达式" prop="expression">
          <el-input 
            v-model="form.expression" 
            type="textarea" 
            :rows="4"
            placeholder="JavaScript表达式，例如: response.status === 200 && response.data.success"
          >
            <template #suffix>
              <el-tooltip content="JavaScript表达式&#10;可用变量: response, variables, statusCode" placement="top">
                <el-icon style="cursor: help"><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
      </div>

      <!-- 执行配置 -->
      <el-form-item label="执行配置">
        <div class="execution-config">
          <el-checkbox v-model="form.continueOnFailure">失败时继续执行</el-checkbox>
          <el-checkbox v-model="form.isEnabled">启用此节点</el-checkbox>
        </div>
      </el-form-item>

      <!-- 条件预览 -->
      <el-form-item label="条件预览">
        <div class="condition-preview">
          <el-tag type="info">{{ getConditionDescription() }}</el-tag>
        </div>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <div class="footer-left">
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>
          删除节点
        </el-button>
      </div>
      <div class="footer-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { QuestionFilled, Delete } from '@element-plus/icons-vue'

const props = defineProps({
  nodeData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['save', 'cancel', 'delete'])

const formRef = ref()

// 表单数据
const form = reactive({
  name: props.nodeData.data?.label || '条件判断',
  conditionType: props.nodeData.data?.config?.conditionType || 'status_code',
  operator: props.nodeData.data?.config?.operator || 'equals',
  targetPath: props.nodeData.data?.config?.targetPath || '',
  expectedValue: props.nodeData.data?.config?.expectedValue || '',
  expression: props.nodeData.data?.config?.expression || '',
  continueOnFailure: props.nodeData.data?.config?.continueOnFailure || false,
  isEnabled: props.nodeData.data?.config?.isEnabled !== false
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入节点名称', trigger: 'blur' }
  ],
  conditionType: [
    { required: true, message: '请选择条件类型', trigger: 'change' }
  ]
}

// 条件类型变化处理
const onConditionTypeChange = () => {
  // 重置相关字段
  form.operator = 'equals'
  form.targetPath = ''
  form.expectedValue = ''
  form.expression = ''
}

// 获取条件描述
const getConditionDescription = () => {
  const { conditionType, operator, targetPath, expectedValue, expression } = form
  
  if (conditionType === 'custom') {
    return expression || '自定义表达式'
  }
  
  const typeLabels = {
    status_code: '响应状态码',
    response_time: '响应时间',
    jsonpath: `JSONPath(${targetPath})`,
    header: `响应头(${targetPath})`,
    body_contains: '响应体包含',
    variable: `变量(${targetPath})`
  }
  
  const operatorLabels = {
    equals: '等于',
    not_equals: '不等于',
    greater_than: '大于',
    less_than: '小于',
    greater_equal: '大于等于',
    less_equal: '小于等于',
    contains: '包含',
    not_contains: '不包含',
    exists: '存在',
    not_exists: '不存在',
    not_empty: '不为空'
  }
  
  const typeLabel = typeLabels[conditionType] || conditionType
  const operatorLabel = operatorLabels[operator] || operator
  
  if (['exists', 'not_exists', 'not_empty'].includes(operator)) {
    return `${typeLabel} ${operatorLabel}`
  }
  
  return `${typeLabel} ${operatorLabel} ${expectedValue || '?'}`
}

// 处理保存
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    const config = {
      conditionType: form.conditionType,
      operator: form.operator,
      targetPath: form.targetPath,
      expectedValue: form.expectedValue,
      expression: form.expression,
      continueOnFailure: form.continueOnFailure,
      isEnabled: form.isEnabled
    }
    
    emit('save', {
      name: form.name,
      ...config
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}

// 处理删除
const handleDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这个节点吗？此操作不可撤销。',
    '删除节点',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    emit('delete', props.nodeData)
  }).catch(() => {
    // 用户取消删除
  })
}
</script>

<style scoped>
.condition-node-config {
  max-height: 70vh;
  overflow-y: auto;
  padding: 16px;
  font-size: 13px;
}

/* 表单标签样式优化 */
.condition-node-config :deep(.el-form-item__label) {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
}

/* 输入框字体大小 */
.condition-node-config :deep(.el-input__inner),
.condition-node-config :deep(.el-select .el-input__inner),
.condition-node-config :deep(.el-textarea__inner) {
  font-size: 13px;
}

.execution-config {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.condition-preview {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  font-size: 12px;
}

.dialog-footer {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.footer-left {
  display: flex;
}

.footer-right {
  display: flex;
}

.dialog-footer .el-button {
  margin-left: 8px;
  font-size: 13px;
}

.footer-left .el-button {
  margin-left: 0;
  margin-right: 8px;
}
</style>